/**
 * Copyright (c) 2014-2016 www.nryuncang.com. All Rights Reserved.
 */
package com.topisv.tms.web.prioritySend;

import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.omg.CORBA.ExceptionList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.OfflineEdiOrder;
import com.topisv.tms.entity.lpn.LPN;
import com.topisv.tms.mybatis.Pagination;
import com.topisv.tms.service.prioritySend.PrioritySendService;
import com.topisv.tms.tools.DataTablesUtils;
import com.topisv.tms.web.base.BaseController;

import aj.org.objectweb.asm.Type;
import net.sf.json.JSONObject;

/**
 * 
 *
 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
 * @version 1.0.0
 */
@Controller
@RequestMapping(value = "/prioritySend")
public class PrioritySendController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(PrioritySendController.class);

	@Autowired
	private PrioritySendService prioritySendService;

	@RequestMapping(value = "v2_query")
	public String query(Model model) {
		return "prioritySend/prioritySend";
	}

	@RequestMapping(value = "v2_queryOrder")
	@ResponseBody
	public Object queryOrder(HttpServletRequest request, HttpServletResponse response) {
		Pagination page = null;
		try {
			String orderType = request.getParameter("orderType");
			String returnsStatus = request.getParameter("returnsStatus");
			Map<String, Object> param = new HashMap<String, Object>();
			if (StringUtils.isNotEmpty(orderType)) {
				param.put("orderSource", orderType);
			}
			if (StringUtils.isNotEmpty(returnsStatus)) {
				param.put("returnStatus", returnsStatus);
			}
			page = prioritySendService.loadPage(param);
		} catch (Exception e) {
			logger.error("error", e);
		}
		return page;
	}

	/**
	 * 批量重新回传
	 * 
	 *
	 * @param ids
	 * @param request
	 * @param response
	 *            [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	@RequestMapping(value = "batchAgainBack", method = RequestMethod.POST)
	public void batchAgainBack(@RequestParam(value = "ids") String[] ids, HttpServletRequest request,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		boolean isLockSuccess = false;
		int failCount = 0;
		try {
			out = response.getWriter();
			json = new JSONObject();

			// 进行重接回传操作
			for (String id : ids) {
				failCount = prioritySendService.batchAgainBack(id) == true ? failCount : (++failCount);
			}

			json.put("status", "1");
			json.put("msg", "共" + ids.length + "单,成功" + (ids.length - failCount) + ",失败" + failCount);
		} catch (Exception e) {
			logger.error("批量重新回传异常:", e);
			json.put("status", "0");
			json.put("msg", "批量重新回传异常,共" + ids.length + "单,成功" + (ids.length - failCount) + ",失败" + failCount);
		} finally {
			// 根据商家、仓库进行解锁操作
			out.print(json.toString());
		}
	}

	/**
	 * 导入订单
	 * 
	 *
	 * @param model
	 * @param lpnType
	 * @param request
	 * @param redirectAttributes
	 * @return [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	@SuppressWarnings({ "unused", "unchecked" })
	@RequestMapping(value = "v2_importExcel")
	public String importExcel(Model model, ServletRequest request, RedirectAttributes redirectAttributes) {
		HttpServletRequest httpRequest = null;
		DiskFileItemFactory factory = null;
		ServletFileUpload upload = null;
		List<FileItem> items = null;
		Workbook rwb = null;

		List<Object> exceptionList = new ArrayList<Object>();// 导入失败的订单
		List<Object> normalList = new ArrayList<Object>();// 导入成功的订单
		String message = "导入成功;";// 导入信息
		try {
			httpRequest = (HttpServletRequest) request;
			httpRequest.setCharacterEncoding("UTF-8");
			factory = new DiskFileItemFactory();
			upload = new ServletFileUpload(factory);
			items = upload.parseRequest(httpRequest);

			Iterator<FileItem> itr = items.iterator();
			int uploadFileCount = 0;
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (!item.isFormField()) {// 非表单字段就是上传处理文件

					if (item.getName() != null && !item.getName().equals("")) {
						uploadFileCount++;
						// 获取Excel文件对象
						InputStream stream = item.getInputStream();

						if (item.getName().endsWith(".xls")) {

							// 解析xls
							rwb = new HSSFWorkbook(stream);

							Sheet sheet = rwb.getSheetAt(0);
							
							//保存excel记录
							message = prioritySendService.saveExcelRows(exceptionList, normalList, message, sheet);

						} else if (item.getName().endsWith(".xlsx")) {

							// 解析xlsx
							rwb = new XSSFWorkbook(stream);

							XSSFSheet sheet = (XSSFSheet) rwb.getSheetAt(0);
							
							//保存excel记录
							message = prioritySendService.saveExcelRows(exceptionList, normalList, message, sheet);

						}
						
						model.addAttribute("normal", normalList);
						model.addAttribute("exception", exceptionList);
						model.addAttribute("message", message);
						model.addAttribute("status", "1");
						model.addAttribute("number", exceptionList.size() + normalList.size());
						log.info("导入成功");
					
					} else {
						log.error("导入文件名为空");
					}

				}
				if (uploadFileCount <= 0) {
					model.addAttribute("status", "2");
					model.addAttribute("message", "没有上传订单文件或订单文件无效或无数据");
					log.error("没有上传订单文件或订单文件无效或无数据");
				}
			}

		} catch (RuntimeException e1) {
			model.addAttribute("status", "2");
			model.addAttribute("message", e1.getMessage());
			log.error("订单导入失败", e1);
		}catch (Exception e2) {	
			model.addAttribute("status", "2");
			model.addAttribute("message", "订单导入数据失败");
			log.error("订单导入失败", e2);
		}
		return "prioritySend/leadOfflineEdiOrderValues";
	}
}
